// --- Copyright (c) 2006-2008 Stefan Kyntchev ---
// This software is written and copyrighted by Stefan Kyntchev 
// and BeyondPod Team members. All rights are reserved.
// Author contact: support@beyondpod.mobi
// ------------------------------------------------------------------------
// This file is part of BeyondPod RSS Feed Reader and Podcast manager
// (www.codeplex.com/BeyondPod) 
// BeyondPod is free software: you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published by 
// the Free Software Foundation, either version 3 of the License, or 
// (at your option) any later version. 
//  
// BeyondPod is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
// GNU General Public License for more details. 
//  
// You should have received a copy of the GNU General Public License
// along with BeyondPod. If not, see <http://www.gnu.org/licenses/>
// ------------------------------------------------------------------------
// COPYRIGHT NOTICE: This copyright notice may NOT be removed, obscured or modified 
// without written consent from the author.
// --- End copyright notice --- 


using System;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;
using svs.Mobile.BeyondScheduler.Core;
using svs.Mobile.BeyondScheduler.Core.Objects;
using svs.Mobile.BeyondScheduler.Core.Objects.Operations;
using svs.Mobile.BeyondScheduler.UI.Properties;

namespace svs.Mobile.BeyondScheduler.UI
{
	public partial class Schedule : Form
	{
		public Schedule()
		{
			InitializeComponent();
		}

		private void OnActionSelected(ScheduledTask action)
		{
			OpenPropertiesDialog(action);
		}

		private void OpenPropertiesDialog(ScheduledTask action)
		{
			TaskProperties dlg = new TaskProperties();
			dlg.SetCurrentAction(action);
			dlg.ShowDialog();

			if (dlg.DialogResult == DialogResult.OK)
			{
				if ( TaskRepository.GetTaskById(action.TaskID) == null)
				{
					TaskRepository.RegisterTask(action);
				}

				if (action.Event.ExistOnDevice)
				{
					TaskRepository.DeleteScheduledTaskFromDevice(action);
				}

				TaskRepository.SetScheduledTaskToDevice(action);

				TasksView.Reload();
				TaskRepository.SaveRepository();
			}
		}

		private void menuExit_Click(object sender, EventArgs e)
		{
			Close();
		}

		private void menuDeleteTask_Click(object sender, EventArgs e)
		{
			if (TasksView.SelectedTask != null)
			{
				TaskRepository.UnregisterTask(TasksView.SelectedTask);
				TasksView.Reload();
				TaskRepository.SaveRepository();
			}
		}

		private void OnLoad(object sender, EventArgs e)
		{
			TasksView.Reload();

			Text = "Scheduled Tasks - " + DateTime.Now.ToString("ddd, MMM d");
		}

		private void OnClosing(object sender, CancelEventArgs e)
		{
		}

		private void menuExecute_Click(object sender, EventArgs e)
		{
			if (TasksView.SelectedTask != null)
			{
				try
				{
					Cursor.Current = Cursors.WaitCursor;
					Application.DoEvents();
					TasksView.SelectedTask.Operation.Execute();
				}
				catch (Exception ex)
				{
					string error =
						string.Format("Failed to execute {0}!\nReason: {1}", TasksView.SelectedTask.Operation, ex.Message);
					MessageBox.Show(error, "Operation Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
					                MessageBoxDefaultButton.Button1);
				}
				finally
				{
					Cursor.Current = Cursors.Default;
				}
			}
		}

		private void menuAddTask_Click(object sender, EventArgs e)
		{
			ScheduledTask task = new ScheduledTask(TaskRepository.GenerateUniqueTaskID());
			task.Event = new Event(DateTime.Now, 0, new TimeSpan(1, 0, 0, 0));
			task.Operation = new OperationNull();
			OpenPropertiesDialog(task);
		}

		private void menuEditTask_Click(object sender, EventArgs e)
		{
			if (TasksView.SelectedTask != null)
				OpenPropertiesDialog(TasksView.SelectedTask);
		}

		private void OnRMenuPopUp(object sender, EventArgs e)
		{
			if (TasksView.SelectedTask == null)
			{
				menuEditTask.Enabled = false;
				menuDeleteTask.Enabled = false;
				menuEnableDisable.Enabled = false;
			}
			else
			{
				menuEditTask.Enabled = true;
				menuDeleteTask.Enabled = true;
				menuEnableDisable.Enabled = true;

				if (TasksView.SelectedTask.Active)
					menuEnableDisable.Text = "Disable Task";
				else
					menuEnableDisable.Text = "Enable Task";
			}
		}

		private void menuEnableDisable_Click(object sender, EventArgs e)
		{
			ScheduledTask t = TasksView.SelectedTask;
			if (t == null)
				return;

			try
			{
				if (t.Active)
				{
					if (t.Event.ExistOnDevice)
						TaskRepository.DeleteScheduledTaskFromDevice(t);

					t.Active = false;
				}
				else
				{
					if (t.Event.StartTime <= DateTime.Now)
					{
						MessageBox.Show("The scheduled time for this task has passed!\nPlease check the task Start Date/Time!",
						                "Invalid Start TIme", MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
						                MessageBoxDefaultButton.Button1);
						return;
					}
					else
					{
						t.Active = true;
						TaskRepository.SetScheduledTaskToDevice(t);
					}
				}

				TaskRepository.SaveRepository();
			}
			catch (Exception ex)
			{
				MessageBox.Show("Unable to update device Data!\n" + ex.Message,
				                "Invalid Start Time", MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
				                MessageBoxDefaultButton.Button1);
			}

			TasksView.Reload();
		}

		private void menuAbout_Click(object sender, EventArgs e)
		{
			string message =
				string.Format(Resources.AboutBeyondSync,
				              Assembly.GetExecutingAssembly().GetName().Version.ToString(), Environment.OSVersion,
				              CoreHelper.GetTotalMemoryUsedAsString());

			MessageBox.Show(message,
			                "About BeyondSchedule", MessageBoxButtons.OK, MessageBoxIcon.Asterisk,
			                MessageBoxDefaultButton.Button1);
		}
	}
}